package com.nx.platform.es.bean.modle.score;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.collections4.MapUtils;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder.FilterFunctionBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.index.query.functionscore.WeightBuilder;

import java.util.Map;

/**
 * @author
 * @since 2016年10月17日
 */
public class GeoDistanceFilterHandler implements ScoreFunctionFieldHandler {

    @Override
    public FilterFunctionBuilder handle(ImmutableMap<String, ?> fieldConfig, Map<String, Object> params) {
        double lon = MapUtils.getDoubleValue(params, "lon", 0d);
        double lat = MapUtils.getDoubleValue(params, "lat", 0d);
        if (Double.doubleToLongBits(lon) == 0 && Double.doubleToLongBits(lat) == 0) {
            return null;
        }
        String fieldName = MapUtils.getString(fieldConfig, "fieldName");
        Preconditions.checkState(!Strings.isNullOrEmpty(fieldName));
        double distance = MapUtils.getDoubleValue(fieldConfig, "distance", 0d);
        Preconditions.checkState(distance > 0, "distance <= 0");
        float weight = MapUtils.getFloatValue(fieldConfig, "weight", 0f);
        if (weight <= 0) {
            return null;
        }
        WeightBuilder function = ScoreFunctionBuilders.weightFactorFunction(weight);
        QueryBuilder filter = QueryBuilders.geoDistanceQuery(fieldName).point(lat, lon).distance(distance, DistanceUnit.METERS);
        return new FilterFunctionBuilder(filter, function);
    }

}
